package com.codebuffer.nowcoder;

public class GetNumberOfK {
    public int GetNumberOfK(int [] array , int k) {
        if(array.length==0){
            return 0;
        }
        int start = 0;
        int end = array.length-1;
        int mid = 0;
        boolean label = true;
        while (start<end){
            mid = (start+end)>>1;
            if(array[mid]==k){
                break;
            }else if(array[mid]> k){
                end = mid-1;
            }else if(array[mid] < k){
                start = mid+1;
            }
        }
        if(start==end && array[start]!=k){
            return 0;
        }
        int count = 1;
        for (int i = 1; ; i++) {
            if(start > mid - i && mid + i > end){
                break;
            }
            if(mid + i<= end && array[mid + i]==k){
                count++;
            }
            if(start <= mid - i && array[mid - i]==k){
                count++;
            }
        }

        return count;
    }

    public static void main(String[] args) {
        GetNumberOfK getNumberOfK = new GetNumberOfK();
        int[] arr = new int[]{1,2,3,3,3,3,4,5};
        System.out.println(getNumberOfK.GetNumberOfK(arr,3));


    }
}
